package com.multithreading.chart1.sleep;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @project_name: java-multithreading
 * @package_name: com.cqb.sleep
 * @ClassName: sleepTest
 * @description: 演示线程在睡眠时拥有的资源监视器资源不会释放
 * Author by cqb, Date on 2020/6/29，7:09
 * PS: Not easy to write code, please indicate.
 */
public class SleepTest {
    /**创建一个独占锁
     *
     */
    private static final Lock lock=new ReentrantLock();
    public static void main(String[] args) throws InterruptedException{
        //创建线程a
        Thread threadA=new Thread(new Runnable() {
            @Override
            public void run() {
                //获取独占锁
                lock.lock();
                try {
                    System.out.println("child threadA is in sleep");
                    Thread.sleep(1000);
                    System.out.println("child threadA is in awake");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }finally {
                    //释放锁
                    lock.unlock();
                }

            }
        });

        //创建线程b
        Thread threadB=new Thread(new Runnable() {
            @Override
            public void run() {
                //获取独占锁
                lock.lock();
                try {
                    System.out.println("child threadB is in sleep");
                    Thread.sleep(1000);
                    System.out.println("child threadB is in awake");
                }catch (InterruptedException ex){
                    ex.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        });

        //启动线程
        threadA.start();
        threadB.start();
    }

}
